package com.ktvme.aspect;

import com.ktvme.annotation.OperationLog;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;

@Slf4j
@Aspect
@Component
public class OperationLogAspect {

    @Around("@annotation(operationLog)")
    public Object around(ProceedingJoinPoint point, OperationLog operationLog) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = null;
        try {
            result = point.proceed();
            recordOperationLog(point, operationLog, System.currentTimeMillis() - startTime, true, null);
            return result;
        } catch (Exception e) {
            recordOperationLog(point, operationLog, System.currentTimeMillis() - startTime, false, e.getMessage());
            throw e;
        }
    }

    private void recordOperationLog(ProceedingJoinPoint point, OperationLog operationLog, 
                                  long executionTime, boolean success, String errorMsg) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            
            String username = request.getHeader("username");
            if (username == null) {
                username = "unknown";
            }

            String logMessage = "操作日志:\n" +
                    "时间: " + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "\n" +
                    "用户: " + username + "\n" +
                    "类型: " + operationLog.operationType() + "\n" +
                    "描述: " + operationLog.description() + "\n" +
                    "方法: " + point.getSignature().toShortString() + "\n" +
                    "参数: " + Arrays.toString(point.getArgs()) + "\n" +
                    "路径: " + request.getRequestURI() + "\n" +
                    "IP: " + request.getRemoteAddr() + "\n" +
                    "耗时: " + executionTime + "ms\n" +
                    "状态: " + (success ? "成功" : "失败") + "\n" +
                    (errorMsg != null ? "错误信息: " + errorMsg : "");

            log.info(logMessage);
        } catch (Exception e) {
            log.error("记录操作日志失败", e);
        }
    }
} 